import React, {useEffect, useRef} from "react";
import * as ECharts from "echarts";
import {createStyles} from "antd-style";

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            background-color: transparent;
        `,
    }
})


interface Props {
    // 宽度
    width: number,
    // 高度
    height: number,
    // 初始化
    graphInit: (instance: ECharts.EChartsType, dom: HTMLDivElement) => void,
    onClick?: () => void
}

const EChartsFC: React.FC<Props> = ({width, height, graphInit, onClick}) => {
    const container = useRef<HTMLDivElement>(null);
    const styles = useStyles().styles

    useEffect(() => {
        if (container.current instanceof HTMLDivElement) {
            const ins = ECharts.init(container.current, 'dark')

            graphInit(ins, container.current)

            return () => {
                ins.dispose()
            }
        }
    }, []);

    useEffect(() => {
        if (!(container.current instanceof HTMLDivElement)) return
        const instance = ECharts.getInstanceByDom(container.current)
        if (instance == null || instance.isDisposed()) return
        instance.resize({width: width, height: height})
    }, [width, height]);

    return (
        <div ref={container}
             className={styles.container}
             style={{width: width, height: height}}
             onClick={() => {
                 onClick && onClick()
             }}
        ></div>
    )
}

export default EChartsFC
